package com.example.lenovo.sbns.Activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloudQueryResult;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.CloudQueryCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.example.lenovo.sbns.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class product_info extends AppCompatActivity {


    private MyAdapter mAdapter;
    private ImageView imageView;
    private RadioGroup radioGroup;
    private RadioButton first,second,third;
    private RadioButton radioButton;
    private TextView declearView;
    private TextView priceView;
    private ExpandableListView expandableListView;
    private List<String> GroupList;
    private List<List<String>> ChildList;
    private String ProductID;
    private String Collection;

    public static void setListViewHeightBasedOnChildren(ExpandableListView listView ) {
        // 获取ListView对应的Adapter
        ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
        if (listAdapter == null) {
            // pre -condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getGroupCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listgroupItem = listAdapter .getGroupView(i, true, null, listView );
            listgroupItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listgroupItem .getMeasuredHeight(); // 统计所有子项的总高度
            for (int j = 0; j < listAdapter.getChildrenCount( i); j++) {
                View listchildItem = listAdapter .getChildView(i, j, false , null, listView);
                listchildItem.measure(0, 0); // 计算子项View 的宽高
                totalHeight += listchildItem.getMeasuredHeight(); // 统计所有子项的总高度
            }
        }

        ViewGroup.LayoutParams params = listView .getLayoutParams();
        params.height = totalHeight + ( listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params );
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_info);

        expandableListView = (ExpandableListView) findViewById(R.id.allInfoList);
        GroupList =new ArrayList<String>();
        ChildList = new ArrayList<List<String>>();

        first = (RadioButton) findViewById(R.id.FirstButtonTwo);
        second = (RadioButton) findViewById(R.id.SecondButtonTwo);
        third = (RadioButton) findViewById(R.id.ThirdButtonTwo);


        Drawable drawable = getResources().getDrawable(R.mipmap.fenxiang);
        drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        second.setCompoundDrawables(null, drawable, null, null);//只放左边
        drawable = getResources().getDrawable(R.mipmap.gouwuche);
        drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
        third.setCompoundDrawables(null, drawable, null, null);//只放左边





        AVOSCloud.initialize(product_info.this, "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");

        //创建一级条目标题
        Map<String, Object> title_1 = new HashMap<String, Object>();
        title_1.put("group", "图文简介");

        //创建一级条目容器
        //图文简介
        List<Map<String, Object>> gruops = new ArrayList<Map<String,Object>>();
        gruops.add(title_1);


        //创建二级条目内容
        //产品图文
        Map<String, Object> content_3 = new HashMap<String, Object>();
        Map<String, Object> content_4 = new HashMap<String, Object>();
        Map<String, Object> content_5 = new HashMap<String, Object>();
        Map<String, Object> content_6 = new HashMap<String, Object>();
        Map<String, Object> content_7 = new HashMap<String, Object>();
        Map<String, Object> content_8 = new HashMap<String, Object>();

        content_3.put("child", R.mipmap.ic_launcher);
        content_4.put("child", R.mipmap.ic_launcher);
        content_5.put("child", R.mipmap.ic_launcher);
        content_6.put("child", R.mipmap.ic_launcher);
        content_7.put("child", R.mipmap.ic_launcher);
        content_8.put("child", R.mipmap.ic_launcher);

        List<Map<String, Object>> childs_1 = new ArrayList<>();
        childs_1.add(content_3);
        childs_1.add(content_4);
        childs_1.add(content_5);
        childs_1.add(content_6);
        childs_1.add(content_7);
        childs_1.add(content_8);

        //存放内容, 以便显示在列表中
        List<List<Map<String, Object>>> childs = new ArrayList<>();
        childs.add(childs_1);

        //适配器匹配内容
        mAdapter = new MyAdapter(
                product_info.this,
                gruops,R.layout.productexten_group,new String[]{"group"},new int[]{R.id.textGroup},
                childs,R.layout.productexten_item,new String[]{"child"},new int[]{R.id.textChild}
        );

        mAdapter.setViewBinder(new MyAdapter.ViewBinder() {

            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                switch (view.getId()) {
                    case R.id.textChild: {
                        if (view instanceof ImageView) {
                            ImageView _view = (ImageView) view;
                            if (data instanceof Integer) {
                                _view.setImageResource((Integer) data);
                            } else if (data instanceof Drawable) {
                                _view.setImageDrawable((Drawable) data);
                            } else {
                                throw new IllegalArgumentException("The Data is Not a Drawable Or Resource Id!");
                            }
                        }

                        return true;
                    }
                }

                return false;
            }
        });



        expandableListView.setAdapter(mAdapter);
        //默认展开
        expandableListView.expandGroup(0);
        //动态计算ExpandableListView的高度
        setListViewHeightBasedOnChildren(expandableListView);

        /*从Intent中获取数据*/
        Intent intent = getIntent();
        ProductID = intent.getStringExtra("ProductID");
        declearView = (TextView) findViewById(R.id.DeclearProduct);
        priceView = (TextView) findViewById(R.id.PriceProduct);

        AVQuery<AVObject> avQuery = new AVQuery<>("ProductInfo");
        avQuery.getInBackground(ProductID, new GetCallback<AVObject>() {
            @Override
            public void done(AVObject avObject, AVException e) {
                // object 就是 id 为 ProductID 的 Todo 对象实例
                System.out.println(avObject.toJSONObject().toString());
                declearView.setText(avObject.getString("productname"));
                priceView.setText(avObject.getString("productprice"));
            }
        });


        radioButton = (RadioButton) findViewById(R.id.FirstButtonTwo);
        AVQuery<AVObject> query = new AVQuery<>("Collection");
        query.whereEqualTo("userID", "123");
        query.whereEqualTo("productID", ProductID);
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (list.isEmpty()) {
                    radioButton.setText("收藏");
                    Drawable drawable = getResources().getDrawable(R.mipmap.flag);
                    drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                    first.setCompoundDrawables(null, drawable, null, null);//只放左边
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.flagclick);
                    drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                    first.setCompoundDrawables(null, drawable, null, null);//只放左边
                    radioButton.setText("取消收藏");
                    Collection = list.get(0).getObjectId();
                }
            }
        });

        imageView = (ImageView) findViewById(R.id.ProductImage);
        imageView.setImageResource(R.mipmap.productimage);

        radioGroup = (RadioGroup) findViewById(R.id.GroupTwo);
        radioGroup.setOnCheckedChangeListener(new RadioGroupCheckedChangeLisitener());


    }

    /**
     * RadioGroup监听器
     */
    public class RadioGroupCheckedChangeLisitener implements RadioGroup.OnCheckedChangeListener{

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            AVObject todo = new AVObject("Collection");
            switch (checkedId) {
                case R.id.FirstButtonTwo: {


                    if(radioButton.getText() == "收藏") {

                        todo.put("userID", "123");
                        todo.put("productID", ProductID);
                        todo.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    // 存储成功
                                } else {
                                    // 失败的话，请检查网络环境以及 SDK 配置是否正确
                                }
                            }
                        });
                        Drawable drawable = getResources().getDrawable(R.mipmap.flagclick);
                        drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                        first.setCompoundDrawables(null, drawable, null, null);//只放左边
                        radioButton.setText("取消收藏");
                    }
                    else{
                        AVQuery.doCloudQueryInBackground("delete from Collection where productID='"+ProductID+"'", new CloudQueryCallback<AVCloudQueryResult>()
                        {
                            @Override
                            public void done(AVCloudQueryResult avCloudQueryResult, AVException e) {
                                System.out.println("delete from Collection where productID='"+ProductID+"'");
                                System.out.println("The ProductID = "+ProductID);
                            }
                        });
                        Drawable drawable = getResources().getDrawable(R.mipmap.flag);
                        drawable.setBounds(0, 0, 80, 80);//第一0是距左边距离，第二0是距上边距离，40分别是长宽
                        first.setCompoundDrawables(null, drawable, null, null);//只放左边
                        radioButton.setText("收藏");
                    }
                    radioButton.setChecked(false);
                    break;
                }
                case R.id.SecondButtonTwo: {



                }
                case R.id.ThirdButtonTwo: {



                }
            }
        }
    }



}
